package com.nehc.nettyserver.netty.handler;

import com.nehc.nettyserver.service.ClientSessionService;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 心跳处理器
 * 
 * @author nehc
 * @date 2023-04-02
 */
@Slf4j
@Sharable
@Component
public class HeartbeatHandler extends ChannelInboundHandlerAdapter {

    @Autowired
    private ClientSessionService sessionService;

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            
            if (event.state() == IdleState.READER_IDLE) {
                log.debug("Client heartbeat timeout, closing connection: {}", ctx.channel().remoteAddress());
                // 移除会话并关闭连接
                sessionService.removeSession(ctx.channel());
                ctx.close();
            }
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        log.error("Heartbeat handler exception: ", cause);
        sessionService.removeSession(ctx.channel());
        ctx.close();
    }
} 